package pers.cj.pdos.controller.other;

import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import pers.cj.pdos.controller.base.BaseController;
import pers.cj.pdos.utils.EncryptDES3;
import pers.cj.pdos.utils.Utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.Base64;

@Controller
@RequestMapping("/login")
public class LoginController extends BaseController {

    @RequestMapping("/login")
    public String login(HttpServletRequest request, Model model, String username,String password) throws Exception {
        //shiro在认证通过后出现错误后将异常信息通过request返回
        //如果登录失败从request中获取认证异常信息，shiroLoginFailure就是shiro异常类的全限定名
        String exceptionClassName = (String) request.getAttribute("shiroLoginFailure");
        if (exceptionClassName != null) {
            if (UnknownAccountException.class.getName().equals(exceptionClassName)) {
                model.addAttribute("errMsg","账号不存在");
            } else if (IncorrectCredentialsException.class.getName().equals(exceptionClassName)) {
                model.addAttribute("errMsg","密码错误");
            }else if (exceptionClassName.equals("randomCodeError")){
                model.addAttribute("errMsg","验证码错误");
            } else {
                model.addAttribute("errMsg","其他错误");
            }
        }

        if (Utils.isEmpty(username) || Utils.isEmpty(password)) {
            String loginAccount = "";
            String loginPassword = "";
            Cookie[] cookies = request.getCookies();
            if(cookies!=null&&cookies.length>0){
                //遍历Cookie
                for(int i=0;i<cookies.length;i++){
                    Cookie cookie = cookies[i];
                    //此处类似与Map有
                    if("loginAccount".equals(cookie.getName())){
                        loginAccount = cookie.getValue();
                    }
                    if("loginPassword".equals(cookie.getName())){
                        EncryptDES3 des = new EncryptDES3();
                        byte[] baseDecode = Base64.getDecoder().decode(cookie.getValue());
                        byte[] bytePass = des.Decryptor(baseDecode);
                        loginPassword = new String(bytePass);// 解密存储的密码
                    }
                }
            }

            model.addAttribute("username",loginAccount);
            //model.addAttribute("password",loginPassword);
        } else {
            model.addAttribute("username",username);
            model.addAttribute("password",password);
        }
        return "login";
    }
}
